package com.xinan.weixin.media;

import com.alibaba.fastjson.JSON;
import com.jfinal.config.JFinalConfig;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.xinan.utils.PropertiesHelper;
import com.xinan.utils.Upload;
import com.xinan.weixin.api.MediaApi;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojing
 * Date: 14-8-2
 * Time: 下午4:40
 * To change this template use File | Settings | File Templates.
 */
public class UploadMediaController extends Controller {
    private static String filePath = "";
    private static String url = "";


    static {
        Properties r = PropertiesHelper.loadProperty("/weixin.properties");
        if (!r.isEmpty()) {
            try {
                filePath = r.getProperty("filePath");
                url = r.getProperty("wxmediaUrl");
            } catch (Exception e) {
                Logger.getLogger(UploadMediaController.class).error("无法读取参数", e);
            }
        } else {
            Logger.getLogger(UploadMediaController.class).error("无法读取 weixin.properties");
        }
    }


    /**
     * 文件上传
     *
     * @throws Exception
     */
    public void upload() throws Exception {
        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "bmp,png,jpeg,jpg,gif");
        extMap.put("voice", "mp3,wma,wav,amr");
        extMap.put("video", " rm,rmvb,wmv,avi,mpg,mpeg,mp4");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf");

        //定义允许上传文件大小
        HashMap<String, Integer> maxMap = new HashMap<String, Integer>();
        maxMap.put("image", 2);  //单位mb
        maxMap.put("voice", 5);
        maxMap.put("video", 10);


        Map result = new HashMap();
        String dirName = getPara("dir") == null ? "image" : getPara("dir");
        String realpath = getRequest().getRealPath("/" + filePath);
        UploadFile uf = getFile("imgFile", realpath);

        String affix_id = "";
        String affix_name = "";
        if (uf != null) {
            affix_name = uf.getFile().getName();
            File file = uf.getFile();
            //检查扩展名
            String fileExt = affix_name.substring(affix_name.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
                result.put("error", 1);
                result.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                file.delete();
            } else {
                // 上传大小判断
                double length = file.length();
                if (maxMap.get(dirName) <= length / 1024 / 1000) {
                    result.put("error", 1);
                    result.put("message", "上传文件超出允许大小。\n只允许" + maxMap.get(dirName) + "M大小。");
                    file.delete();
                } else {
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    affix_id = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                    File savefile = new File(new File(realpath), affix_id);
                    FileUtils.copyFile(file, savefile);
                    if (file.exists()) {
                        file.delete();
                    }
                    //上传微信服务器用
//                    String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
//                    System.out.println("==============" + accessToken);
//                    String urls = url + filePath + "/" + affix_id;
//                    System.out.println("==============" + urls);
//
//                    RecevieMedia recevieMedia = MediaApi.uploadMedia(accessToken, "image", urls);
//                    String errocode = recevieMedia.getErrcode();
//                    String errmsg = recevieMedia.getErrmsg();
//                    String medaid = recevieMedia.getMedia_id();
//                    String createdate = recevieMedia.getCreated_at();
//                    long unixLong = 0;
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String sd = "";
//                    if (createdate != null) {
//                        sd = sdf.format(new Date(Long.parseLong(createdate) * 1000));
//                    }
//                    if (medaid != null) {
                        // 插入图片信息表
                        getModel(WxImg.class).set("img", affix_id).set("media_id", "").save();
                        result.put("error", 0);
//                        System.out.println("==============" + medaid);
                        //linux文件路径应该为"\"
                        result.put("url", JFinal.me().getContextPath()+"/"+filePath+"/"+affix_id);
                        result.put("message", "上传成功。");

//                    } else {
//                        // 删除文件
//                        savefile.delete();
//                        result.put("error", 1);
//                        result.put("message", "上传失败。失败代码：" + errmsg + "");
//                    }

                }

            }
        } else {
            result.put("error", 1);
            result.put("message", "请选择文件");
        }
        render(new JsonRender(JSON.toJSONString(result)).forIE());
    }

    /**
     * 文件管理
     */
    public void manageImg() {
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
        String currentPath = getRequest().getRealPath("/" + filePath) + File.separator;
        File currentPathFile = new File(currentPath);
        List<Hashtable> fileList = new ArrayList<Hashtable>();
        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }
        //排序形式，name or size or type
        String order = getPara("order") != null ? getPara("order").toLowerCase() : "name";

        Map result = new HashMap();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", "");
        result.put("current_url", JFinal.me().getContextPath() + "/" + filePath + "/");
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        System.out.println(JSON.toJSONString(result));
        renderJson(JSON.toJSONString(result));
    }


}
